package com.rds.benchmark.operator;

import com.rds.benchmark.util.MakeValue;
import io.lettuce.core.api.sync.RedisCommands;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;

import java.io.IOException;

public class StringLettuceOperator extends TypeOperatorBase {

    private RedisAdvancedClusterCommands<String, String> clusterCommands;
    private RedisCommands<String, String> redisCommands;
    private String key;

    private final String value = MakeValue.value;

    @Override
    public void init(Object conn, String key, int idx,String mode) {
        if(conn instanceof RedisAdvancedClusterCommands)
            this.clusterCommands = (RedisAdvancedClusterCommands) conn;
        if(conn instanceof RedisCommands)
            this.redisCommands = (RedisCommands) conn;
        this.key = key;
    }

    @Override
    public Long clear() {
        Long del = 0L;
        if(redisCommands != null)
            del = redisCommands.del(key);
        else if(clusterCommands != null)
            del = clusterCommands.del(key);
        return del;
    }

    @Override
    public void operate() throws IOException {
        if(redisCommands != null){
            redisCommands.set(key, value);

            String msg = redisCommands.get(key);
            if (!value.equals(msg)) {
                times += 2;
                throw new IOException("set value = '" + value + "', but get value = '" + msg + "'");
            } else {
                redisCommands.del(key);
                times += 3;
            }
        }else if(clusterCommands != null){
            clusterCommands.set(key, value);

            String msg = clusterCommands.get(key);
            if (!value.equals(msg)) {
                times += 2;
                throw new IOException("set value = '" + value + "', but get value = '" + msg + "'");
            } else {
                clusterCommands.del(key);
                times += 3;
            }
        }
    }
}
